from pex import toml
from typing import Dict, List, Optional

from logger import logger
from tools.git_client import GitClient
from tools.owner_config_mgr import OwnerConfigMgr
from tools.webhook import WebHook

LOGGER = logger.CustomLogger()

CHECK_RESULT_PASS = "pass"
CHECK_RESULT_FAIL = "fail"

class BaseEvent:
    """
    所有event的基类。

    event处理分为三个阶段：
    1. pre_execute：检查event是否应该执行，做一些权限/分支校验等
    2. execute：执行具体的动作，如加分/门禁检查/更新数据库等

    每个event必须重写以下字段：
    - event_name_zh：事件中文名（在基类的generate_statement时用到）
    - event_name_en：事件英文名（在基类的generate_statement时用到）
    必须重写以下函数：
    - def execute：具体执行事件逻辑，若执行完需要评论回复则返回True，否则返回False，需要在逻辑内对failed进行赋值，表示执行成功或者失败
    可选重写以下函数：
    - def pre_execute：校验事件是否应该执行，不重写默认为True
    """
    def __init__(self, debug_mode=False, git_client=None, cfg=None, user_agent=None):
        # 一些工具，只需初始化一次
        self.git_client: GitClient = git_client
        self.debug_mode = debug_mode
        self.cfg = cfg
        self.OCM = OwnerConfigMgr(user_agent)
        self.hook: Optional[WebHook] = None
        self.keyword_map = {
            "result": {"zh": ["成功。", "失败。"], "en": [" passed.", " failed."]},
        }

        # 个性化配置
        self.event_name_zh: str = ""
        self.event_name_en: str = ""
        self.failed = False
        self.comment = ""

    def set_hook(self, hook: WebHook):
        self.hook = hook

    def generate_html_table(self,
                            data: List[Dict],
                            headers: List[str] = None,
                            caption: str = None,
                            border: bool = True,
                            zebra: bool = True
                            ) -> str:
        """
        生成带样式的HTML表格
        :param data: 数据列表(每个字典代表一行)
        :param headers: 自定义表头(默认使用字典键)
        :param caption: 表格标题
        :param border: 是否显示边框
        :param zebra: 是否启用斑马条纹样式
        :return: 完整HTML字符串
        """
        if not data:
            return "<table><tr><td>No data</td></tr></table>"

        headers = headers or list(data[0].keys())
        style = "border-collapse: collapse; width: 100%;"
        if border:
            style += " border: 1px solid #ddd;"

        html = [f'<table style="{style}">']

        if caption:
            html.append(f'<caption style="padding:10px;font-weight:bold">{caption}</caption>')

        # 表头
        html.append('<tr style="background-color:#f2f2f2">')
        for h in headers:
            html.append(f'<th style="padding:12px;text-align:left">{h}</th>')
        html.append('</tr>')

        # 数据行
        for i, row in enumerate(data):
            row_style = "background-color: #f9f9f9" if zebra and i % 2 else ""
            html.append(f'<tr style="{row_style}">')
            for h in headers:
                val = str(row.get(h, ''))
                html.append(f'<td style="padding:8px;border-bottom:1px solid #ddd">{val}</td>')
            html.append('</tr>')

        html.append('</table>')
        return '\n'.join(html)

    def get_comment(self) -> str:
        return self.comment

    def pre_execute(self) -> bool:
        return True

    def execute(self):
        raise NotImplementedError("子类必须实现execute方法")

    def get_admin_token(self):
        return list(self.cfg.get("accounts", {}).get("admin_user").values())[0]
